<template>
  <div class="home-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>回收站</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="toolbar">
      <div class="button-group">
        <el-button
          type="warning"
          :icon="RefreshLeft"
          @click="onBatchRestore"
          :disabled="selectedIds?.length == 0"
          >恢复</el-button
        >
        <el-button
          type="danger"
          :icon="Close"
          @click="onBatchDelete"
          :disabled="selectedIds?.length == 0"
          >清除</el-button
        >
        <el-button type="primary" :icon="Refresh" @click="onRefresh"
          >刷新</el-button
        >
      </div>
      <div class="search-input">
        <el-input
          v-model="searchText"
          prefix-icon="Search"
          placeholder="搜索文件"
        />
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="filteredTableData"
      ref="multipleTableRef"
      row-key="id"
      :default-sort="{ prop: 'deletedAt', order: 'descending' }"
      @selection-change="onSelectionChange"
    >
      <!-- 选择框 -->
      <el-table-column type="selection" width="48" />
      <!-- 文件图标 -->
      <el-table-column
        prop="type"
        sortable
        :sort-orders="['ascending', 'descending']"
        label="类型"
        width="55"
        class-name="icon-column"
      >
        <template #default="{ row }">
          <svg class="file-icon" aria-hidden="true">
            <use :xlink:href="`#${getFileIconId(row.type)}`" />
          </svg>
        </template>
      </el-table-column>
      <!-- 文件名 -->
      <el-table-column
        prop="filename"
        sortable
        :sort-orders="['ascending', 'descending']"
        label="文件名"
        min-width="100"
        class-name="filename-column"
      >
        <template #default="{ row }">
          <span @click="onFileInfo(row)">
            {{ row.filename }}
          </span>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column
        label="操作"
        min-width="100"
        align="right"
        v-if="!isFold"
      >
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button link type="info" size="small" @click="onFileInfo(row)"
              >详情</el-button
            >
            <el-popconfirm
              title="确定要恢复吗?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="() => onRestore(row)"
            >
              <template #reference>
                <el-button link type="warning" size="small">恢复</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
              title="确定要彻底删除吗?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="() => onDelete(row)"
            >
              <template #reference>
                <el-button link type="danger" size="small">清除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
      <!-- 文件大小 -->
      <el-table-column
        prop="size"
        sortable
        :sort-orders="['ascending', 'descending']"
        label="大小"
        width="150"
        v-if="!isFold"
      >
        <template #default="{ row }">
          {{ formatFileSize(row.size) }}
        </template>
      </el-table-column>
      <!-- 删除时间 -->
      <el-table-column
        prop="deletedAt"
        sortable
        :sort-orders="['ascending', 'descending']"
        label="删除时间"
        width="150"
        v-if="!isFold"
      >
        <template #default="{ row }">
          {{ formatToDateTime(row.deletedAt) }}
        </template>
      </el-table-column>
      <!-- 展开折叠 -->
      <el-table-column type="expand" v-if="isFold">
        <template #default="props">
          <div class="expand-content">
            <div class="expand-info">
              <el-text type="info">{{
                formatToDateTime(props.row.deletedAt)
              }}</el-text>
              <el-text type="info">{{
                formatFileSize(props.row.size)
              }}</el-text>
            </div>
            <el-button-group>
              <el-button type="info" size="small" @click="onFileInfo(props.row)"
                >详情</el-button
              >
              <el-popconfirm
                title="确定要恢复吗?"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="() => onRestore(props.row)"
              >
                <template #reference>
                  <el-button type="warning" size="small">恢复</el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm
                title="确定要彻底删除吗?"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="() => onDelete(props.row)"
              >
                <template #reference>
                  <el-button type="danger" size="small">清除</el-button>
                </template>
              </el-popconfirm>
            </el-button-group>
          </div>
        </template>
      </el-table-column>
      <!-- 空状态 -->
      <template #empty>
        <el-empty description="该目录下没有任何内容" />
      </template>
    </el-table>
  </div>

  <FileInfoDialog ref="fileInfoDialogRef" />
</template>
<script setup>
import { Refresh, RefreshLeft, Close } from "@element-plus/icons-vue";
import { onMounted, ref, computed } from "vue";
import {
  getRecycleApi,
  restoreFileApi,
  restoreFilesApi,
  deleteFileApi,
  deleteFilesApi,
} from "../api";
import { formatToDateTime, formatFileSize } from "../utils/FormatUtil";
import Confirm from "../utils/Confirm";
import { getFileIconId } from "../utils/FileIconId";
import FileInfoDialog from "../components/FileInfoDialog.vue";
import { useWindowSize } from "@vueuse/core";
import { ElMessage } from "element-plus";

const { width } = useWindowSize();
const isFold = computed(() => width.value < 900);

const multipleTableRef = ref(null);

const tableData = ref([]); //表格数据
const selectedIds = ref([]); //选中的行id
const searchText = ref("");
const loading = ref(false);

const filteredTableData = computed(() => {
  return tableData.value.filter((item) => {
    return item.filename.includes(searchText.value);
  });
});

const fileInfoDialogRef = ref(null);

const loadData = async () => {
  loading.value = true;
  try {
    const res = await getRecycleApi();
    tableData.value = res.data;
  } catch (error) {
    console.error("获取回收站文件失败:", error);
    throw error;
  } finally {
    loading.value = false;
  }
};

const onRefresh = async () => {
  try {
    await loadData();
    ElMessage.success("刷新成功");
  } catch (error) {
    console.error("刷新失败:", error);
  }
};

const onSelectionChange = (selection) => {
  selectedIds.value = selection.map((item) => item.id);
};

const onFileInfo = (row) => {
  fileInfoDialogRef.value.open(row);
};

const onRestore = async (row) => {
  try {
    await restoreFileApi(row.id);
    loadData();
  } catch (error) {
    console.error("恢复文件失败:", error);
  }
};

const onBatchRestore = () => {
  Confirm("确定要恢复这些文件吗?", async () => {
    try {
      await restoreFilesApi(selectedIds.value);
      loadData();
    } catch (error) {
      console.error("恢复文件失败:", error);
    }
  });
};
const onDelete = async (row) => {
  try {
    await deleteFileApi(row.id);
    loadData();
  } catch (error) {
    console.error("删除文件失败:", error);
  }
};

const onBatchDelete = () => {
  Confirm("确定要彻底删除这些文件吗?", async () => {
    try {
      await deleteFilesApi(selectedIds.value);
      loadData();
    } catch (error) {
      console.error("删除文件失败:", error);
    }
  });
};
onMounted(loadData);
</script>

<style scoped>
:deep(.icon-column .cell) {
  padding: 0px !important;
}
:deep(td.filename-column .cell:hover) {
  text-decoration: underline;
}
:deep(td.filename-column .cell) {
  cursor: pointer;
}
</style>
